﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;

public partial class CRM_Store_ERP_CustomerReturnEdit : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int c = BindCenterStore(Store_Rome, Request.QueryString["ptabid"]);
            if (c > 0)
                extcomb_StoreRoomId.SelectedIndex = 0;
            string objid = ViewState_ObjID = string.IsNullOrEmpty(Request.QueryString["ObjId"]) ? "Add" : Request.QueryString["ObjId"];
            ShowEditInfo(objid);
        }
    }

    private void ShowEditInfo(string objid)
    {
        if (objid == "Add")
        {
            exttxtf_InUserName.Text = BS_LoginUserName;
            exthidn_InUser.Text = BS_LoginUserID;
            exttxtf_InDate.Text = DateTime.Now.ToDateTimeString();
        }
        else
        {
            var planDataTable = CRMMis.BLL.ERP_CustomerReturn.GetList("CustomerReturnId=" + objid).Tables[0];
            if (planDataTable.Rows.Count > 0)
            {
                DataRow row = planDataTable.Rows[0];
                int planState = Convert.ToInt32(row["State"]);
                //根据状态控制
                if (planState != 1)
                    extBtn_CheckInfo.Hidden = true;
                if (planState > 0)
                {
                    extBtn_SubmitInfo.Hidden = true;
                    extBtn_Save.Hidden = true;
                    extBtn_AddItem.Hidden = extBtn_DeleteItem.Hidden = true;
                    SetContainerReadOnly(formPanel, true);
                    gridPanel_listdata.ColumnModel.Columns[1].Editable =                //商品名称
                        gridPanel_listdata.ColumnModel.Columns[5].Editable = false;     //数量
                }
                if (planState > 1)
                {
                    extBtn_CheckInfo.Hidden = true;
                }
                SetContainer(formPanel, planDataTable);
                //单独绑定客户
                DataTable suppData = CRMMis.BLL.ERP_Customer.GetList("CustomerId=" + row["CustomerId"], "CustomerName,Spell,Address").Tables[0];
                Store_Customer.DataSource = suppData;
                Store_Customer.DataBind();

                var planDetail = CRMMis.BLL.ERP_CustomerReturnDetail.GetList(" DCustomerReturnId=" + objid).Tables[0];
                Store1.DataSource = planDetail;
                Store1.DataBind();
                extcomb_CustomerId.ReadOnly = extcomb_StoreRoomId.ReadOnly = planDetail.Rows.Count > 0;
            }
        }
    }

    [DirectMethod]
    public void BindCargoComb(string searchText)
    {
        string sqWhere = " CusDetailState=1 and CustomId='"
            + Convert.ToInt32(extcomb_CustomerId.Value) + 
            "' and StoreRoomId=" + Convert.ToInt32(extcomb_StoreRoomId.Value);
        if (!string.IsNullOrEmpty(searchText))
        {
            sqWhere += " and( CargoName like '%" + FilterSpecChar(searchText) + "%' or Spell like '%" + FilterSpecChar(searchText) + "%') ";
        }
        var datatable = CRMMis.BLL.ERP_StockDetail.GetListCustomer(sqWhere, " CargoName asc");
        store_Cargo.DataSource = datatable;
        store_Cargo.DataBind();
    }

    /// <summary>
    /// 保存，
    /// </summary>
    /// <param name="jsonData"></param>
    /// <param name="type">0,保存;1,提交;2,审核</param>
    [DirectMethod]
    public void SaveData(string jsonData,int type)
    {
        List<CRMMis.Model.ERP_CustomerReturnDetail> details = JSON.Deserialize<List<CRMMis.Model.ERP_CustomerReturnDetail>>(jsonData);
        CRMMis.Model.ERP_CustomerReturn returnModel;
        if (ViewState_ObjID == "Add")
        {
            returnModel = new CRMMis.Model.ERP_CustomerReturn();
            returnModel.CustomerReturnId = CRMMis.BLL.ERP_CustomerReturn.GetNewID();
            returnModel.CustomerReturnNo = GetBusinessNo("ST", "ERP_CustomerReturnST", Convert.ToInt32(extcomb_StoreRoomId.Value).ToString("000"));
            //returnModel.DeliveryNo = GetBusinessNo("SH", "ERP_CustomerReturnDeliverySH", Convert.ToInt32(extcomb_CustomerId.Value).ToString("000"));
            returnModel.InUser = BS_LoginUserID;
            returnModel.InDate = exttxtf_InDate.Text.Trim();
            returnModel.State = 0;
            if (type == 1)
                returnModel.State = 1;    //提交
        }
        else
        {
            returnModel = CRMMis.BLL.ERP_CustomerReturn.GetModel(Convert.ToInt32(ViewState_ObjID));
            if (type == 1)
            {
                if (returnModel.State == 0)
                    returnModel.State = 1;    //提交
                else
                {
                    X.Msg.Alert("系统提示", "提交失败！当前记录已经提交").Show();
                    return;
                }
            }
            else if (type == 2)
            {
                if (returnModel.State == 1)
                    returnModel.State = 2;    //审核
                else
                {
                    X.Msg.Alert("系统提示", "审核失败！当前记录已经审核").Show();
                    return;
                }
            }

        }
        if (type < 2)
        {
            returnModel.StoreRoomId = Convert.ToInt32(extcomb_StoreRoomId.Value);
            returnModel.CustomerId = Convert.ToInt32(extcomb_CustomerId.Value);
            returnModel.Remark = exttxtf_Remark.Text.Trim();
            returnModel.Comment = exttxtf_Comment.Text.Trim();
        }
        CommonLib.BLL.MyTransaction myTrans = new CommonLib.BLL.MyTransaction();
        myTrans.BeginTransaction();
        try
        {
            if (ViewState_ObjID == "Add")
            {
                CRMMis.BLL.ERP_CustomerReturn.Add(myTrans, returnModel);
            }
            else
            {
                CRMMis.BLL.ERP_CustomerReturn.Update(myTrans, returnModel);
                //删除子表
                if (type < 2)
                    CRMMis.BLL.ERP_CustomerReturnDetail.DeleteFK(myTrans, "DCustomerReturnId = " + returnModel.CustomerReturnId);
                //处理审核
                if (type == 2)
                    CheckInfo(myTrans, returnModel);
            }
            if (type < 2)
            {
                int orderNo = 0;
                foreach (CRMMis.Model.ERP_CustomerReturnDetail detailModel in details)
                {
                    orderNo++;
                    detailModel.DetailId = CRMMis.BLL.ERP_CustomerReturnDetail.GetNewID();
                    detailModel.DCustomerReturnId = returnModel.CustomerReturnId;
                    detailModel.OrderId = orderNo;

                    CRMMis.BLL.ERP_CustomerReturnDetail.Add(myTrans, detailModel);
                }
            }
            myTrans.CommitTran();
            ViewState_ObjID = returnModel.CustomerReturnId.ToString();
            exttxtf_CustomerReturnNo.Text = returnModel.CustomerReturnNo;

            string handler = "";
            if (type > 0)
                handler = "closeCurrTab();";
            X.Msg.Alert("系统提示", "保存成功！", handler).Show();
        }
        catch(Exception ex)
        {
            myTrans.RollBackTran();
            X.Msg.Alert("系统提示", "保存失败！</br>" + ex.Message).Show();
        }
    }

    #region 客户选择

    protected void StoreCustomer_Refresh(object sender, StoreRefreshDataEventArgs e)
    {
        var qStr = GetCustomerQryString();
        int recordcount = CRMMis.BLL.ERP_Customer.GetRecorderCount(qStr);
        int PageSize = extcomb_CustomerId.PageSize;
        int CurPage = e.Start / PageSize + 1;
        e.Total = recordcount;
        DataTable suppData = CRMMis.BLL.ERP_Customer.GetPageList(PageSize, CurPage, qStr, "CustomerName,Spell,Address").Tables[0];
        Store_Customer.DataSource = suppData;
        Store_Customer.DataBind();
    }

    private string GetCustomerQryString()
    {
        string StrSql = "DelState=0 ";
        string selText = FilterSpecChar(extcomb_CustomerId.SelectedItem.Text.Trim());
        if (!string.IsNullOrEmpty(selText))
            StrSql += " and ( CustomerName like '%" + selText + "%' or Spell like '%" + selText + "%') ";
        return StrSql;
    }

    #endregion


    /// <summary>
    /// 处理审核
    /// </summary>
    /// <param name="myTrans"></param>
    /// <param name="returnModel"></param>
    public void CheckInfo(CommonLib.BLL.MyTransaction myTrans, CRMMis.Model.ERP_CustomerReturn returnModel)
    {
        returnModel.CheckUser = BS_LoginUserID;
        returnModel.CheckDate = DateTime.Now.ToString();
        returnModel.State = 2;
        CRMMis.BLL.ERP_CustomerReturn.Update(myTrans, returnModel);

        var ReturnList = CRMMis.BLL.ERP_CustomerReturnDetail.GetList(myTrans, " DCustomerReturnId=" + returnModel.CustomerReturnId, "OrderId").Tables[0];
        foreach (DataRow row in ReturnList.Rows)
        {
            CRMMis.Model.ERP_BusinessLog BusModel = new CRMMis.Model.ERP_BusinessLog();
            BusModel.LogId = CRMMis.BLL.ERP_BusinessLog.GetNewID();
            BusModel.ActionId = 3;
            BusModel.ActionName = "客户退货";
            BusModel.ActionUser = returnModel.InUser;
            BusModel.StoreRoom_Id = returnModel.StoreRoomId.ToString();
            BusModel.ActionDate = returnModel.CheckDate;
            //ERP_StockDetail 表
            var stockDetail = CRMMis.BLL.ERP_StockDetail.GetModel(myTrans,Convert.ToInt32(row["ItemId"]));
            if (stockDetail != null)
            {
                stockDetail.Count += Convert.ToInt32(row["Count"]);
                CRMMis.BLL.ERP_StockDetail.Update(myTrans, stockDetail);
            }
            //ERP_StockInfo 表
            var model = CRMMis.BLL.ERP_StockInfo.GetModel(myTrans, stockDetail.StoreId);
            BusModel.DetailId = model.DetailId;
            DataTable dt = CRMMis.BLL.ERP_Cargo_Detail.GetList("DetailId=" + model.DetailId).Tables[0];
            BusModel.CargoName = dt.Rows[0]["CargoName"].ToString();
            BusModel.Spec = dt.Rows[0]["Spec"].ToString();
            BusModel.Area = dt.Rows[0]["Area"].ToString();
            BusModel.Version = dt.Rows[0]["Version"].ToString();
            BusModel.ProduceName = dt.Rows[0]["ProduceName"].ToString();
            BusModel.BatchNo = row["BatchNo"].ToString();
            BusModel.SupplyPrice = decimal.Parse(dt.Rows[0]["SupplyPrice"].ToString());
            BusModel.CustomId = returnModel.CustomerId;
            if (model != null)
            {
                BusModel.CurCount = model.Count;
                BusModel.Count = Convert.ToInt32(row["Count"]);
                model.Count += Convert.ToInt32(row["Count"]);
                CRMMis.BLL.ERP_StockInfo.Update(myTrans, model);
            }
            BusModel.State = 0;
            BusModel.BusniessNo = returnModel.CustomerReturnNo;
            CRMMis.BLL.ERP_BusinessLog.Add(myTrans, BusModel);
        }
    }

}